// knexfile.js
const path = require('path')
const KeyManager = require('./src/main/key-manager')

// 创建密钥管理器实例
let keyManager
try {
  keyManager = new KeyManager()
  console.log('在knexfile.js中的密钥管理器初始化成功')
} catch (error) {
  console.warn('在knexfile.js中的密钥管理器初始化失败，使用默认配置:', error.message)
}

// 获取数据库密钥
const getDatabaseKey = () => {
  if (keyManager) {
    const key = keyManager.getDatabaseKey()
    console.log('使用安全生成的密钥，长度:', key ? key.length : 0)
    return key
  }
  // 后备密钥（仅在开发环境下使用）
  console.warn('使用后备密钥，生产环境下不安全！')
  return 'dev_default_key_for_development_only_change_in_production'
}

module.exports = {
  development: {
    client: 'sqlite3',
    connection: {
      filename: path.join(__dirname, 'database', 'dev.sqlite3')
    },
    migrations: {
      directory: path.join(__dirname, 'database', 'migrations')
    },
    seeds: {
      directory: path.join(__dirname, 'database', 'seeds')
    },
    useNullAsDefault: true,
    pool: {
      afterCreate: function(conn, done) {
        const key = getDatabaseKey()
        console.log(`knexfile.js: 为新连接设置加密密钥，长度: ${key.length}`)
        
        // 设置加密密钥
        conn.run(`PRAGMA key = '${key}'`, (err) => {
          if (err) {
            console.error('knexfile.js: 设置数据库密钥失败:', err)
            done(err, conn)
            return
          }
          
          // 设置SQLCipher参数
          const pragmas = [
            'PRAGMA cipher_compatibility = 4',
            'PRAGMA cipher_page_size = 4096',
            'PRAGMA kdf_iter = 256000',
            'PRAGMA cipher_hmac_algorithm = HMAC_SHA512',
            'PRAGMA cipher_kdf_algorithm = PBKDF2_HMAC_SHA512'
          ]
          
          let completed = 0
          pragmas.forEach(pragma => {
            conn.run(pragma, (pragmaErr) => {
              if (pragmaErr) {
                console.warn(`knexfile.js: 设置PRAGMA失败 (${pragma}):`, pragmaErr.message)
              }
              completed++
              if (completed === pragmas.length) {
                // 测试连接
                conn.get('SELECT 1 as test', (testErr) => {
                  if (testErr) {
                    console.error('knexfile.js: SQLCipher连接测试失败:', testErr)
                  } else {
                    console.log('knexfile.js: SQLCipher连接设置成功')
                  }
                  done(testErr, conn)
                })
              }
            })
          })
        })
      }
    }
  },

  production: {
    client: 'sqlite3',
    connection: {
      filename: path.join(__dirname, 'database', 'prod.sqlite3')
    },
    migrations: {
      directory: path.join(__dirname, 'database', 'migrations')
    },
    seeds: {
      directory: path.join(__dirname, 'database', 'seeds')
    },
    useNullAsDefault: true,
    pool: {
      afterCreate: function(conn, done) {
        const key = getDatabaseKey()
        console.log(`knexfile.js: 为新连接设置加密密钥，长度: ${key.length}`)
        
        // 设置加密密钥
        conn.run(`PRAGMA key = '${key}'`, (err) => {
          if (err) {
            console.error('knexfile.js: 设置数据库密钥失败:', err)
            done(err, conn)
            return
          }
          
          // 设置SQLCipher参数
          const pragmas = [
            'PRAGMA cipher_compatibility = 4',
            'PRAGMA cipher_page_size = 4096',
            'PRAGMA kdf_iter = 256000',
            'PRAGMA cipher_hmac_algorithm = HMAC_SHA512',
            'PRAGMA cipher_kdf_algorithm = PBKDF2_HMAC_SHA512'
          ]
          
          let completed = 0
          pragmas.forEach(pragma => {
            conn.run(pragma, (pragmaErr) => {
              if (pragmaErr) {
                console.warn(`knexfile.js: 设置PRAGMA失败 (${pragma}):`, pragmaErr.message)
              }
              completed++
              if (completed === pragmas.length) {
                // 测试连接
                conn.get('SELECT 1 as test', (testErr) => {
                  if (testErr) {
                    console.error('knexfile.js: SQLCipher连接测试失败:', testErr)
                  } else {
                    console.log('knexfile.js: SQLCipher连接设置成功')
                  }
                  done(testErr, conn)
                })
              }
            })
          })
        })
      }
    }
  }
}